package com.it.controller;

import com.it.pojo.ClShoppingCar;
import com.it.pojo.LinkFoodCart;
import com.it.pojo.SysUser;
import com.it.service.ClShoppingCarService;
import com.it.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Controller
 *   作用1： 将当前对象的创建交给spring管理
 *   作用2：作为控制层代码的标识
 */
@Controller
public class SysUserController {

	private static final Logger logger = LoggerFactory.getLogger(SysUserController.class);

	@Autowired	//自动注入(由spring创建当前对象并为属性赋值)
	private SysUserService sysUserService;

	@Autowired
	private ClShoppingCarService clShoppingCarService;

	/** 0.1.登录 */
	@RequestMapping("/loginUser")
	public String loginUser(HttpServletRequest request, HttpServletResponse response){
		try{
			//调用service层的findAll方法，查询所有的用户信息
			String account = request.getParameter("account");
			String password = request.getParameter("password");
			String roleId = request.getParameter("roleId");

			SysUser user = sysUserService.findByAccountAndPasswordAndRoleId(account, password, roleId);

			HttpSession session = request.getSession();
			if(user != null){

				List<ClShoppingCar> carts = clShoppingCarService.findByUserId(user.getId());

				if(carts != null && carts.size() > 0){
					ClShoppingCar cart = carts.get(0);
					session.setAttribute("cartId", cart.getId());
					user.setCart(cart);

					/**
					 * 餐桌里的菜品（关联关系）
					 */
					if(cart.getLinkFoodCarts() != null && cart.getLinkFoodCarts().size() > 0){
						String foodIds = "";
						String linkFoodCartIds = "";
						for(LinkFoodCart link:cart.getLinkFoodCarts()){
							foodIds += link.getFoodId() + ", ";
							linkFoodCartIds += link.getId() + ", ";
						}
						session.setAttribute("foodIds", foodIds);
						session.setAttribute("linkFoodCartIds", linkFoodCartIds);
					}

				}

				user.setLastTimeLogin(new Date());
				Long loginNum = user.getLoginNum();
				user.setLoginNum(loginNum++);
				user.setState(1);
				int i = sysUserService.updateById(user);
				if(i > 0){
					//将所有用户信息的list集合存入model中，带到JSP显示
					session.setAttribute("isLogin", "true");
					session.setAttribute("loginUserId", user.getId());
					session.setAttribute("loginAccount", user.getAccount());
					session.setAttribute("loginUserName", user.getName());
					session.setAttribute("loginUserRoleId", user.getRoleId());
					return "index";
				}
			}
			session.setAttribute("isLogin", "false");
		} catch (RuntimeException e){
			e.printStackTrace();
			logger.warn("登录失败。");
		}
		return "login";
	}

	/** 0.2.注销 */
	@RequestMapping("/logout")
	public void logout(HttpServletRequest request, HttpServletResponse response){
		//调用service层的findAll方法，查询所有的用户信息
		HttpSession session = request.getSession();
		session.setAttribute("isLogin", "false");
	}

	/** 1.查询所有用户信息 */
	@RequestMapping("/sysUserList")
	public String sysUserList(HttpServletRequest request, Model model){
	    HttpSession session = request.getSession();

        String loginUserId = (String) session.getAttribute("loginUserId");
        String loginUserRoleId = (String) session.getAttribute("loginUserRoleId");

        List<SysUser> list = new ArrayList<SysUser>();
        if(loginUserRoleId.equals("1")){
            //调用service层的findAll方法，查询所有的用户信息
            list = sysUserService.findAll();
        }else{
            //调用service层的findAll方法，查询所有的用户信息
            SysUser user = sysUserService.findById(loginUserId);
            list.add(user);
        }

		//将所有用户信息的list集合存入model中，带到JSP显示
		model.addAttribute("list", list);

		return "sys/user/list";
	}

	/**
	 * 2.根据id删除用户信息
	 */
	@RequestMapping("/sysUserDelete")
	public String sysUserDelete(String id){
		//调用deleteById方法, 根据id删除用户
		sysUserService.deleteById(id);
		
		return "redirect:/sysUserList";
	}
	
	/** 3.添加用户信息 */
	@RequestMapping("/sysUserAdd")
	public String sysUserAdd(SysUser sysUser){
		//System.out.println(sysUser);
		//1.调用SysUserService层的addSysUser方法, 添加用户信息
		sysUserService.addSysUser(sysUser);
		
		return "redirect:/sysUserList";
	}
	
	/** 4.根据id修改用户信息
	 *  4.1.先根据id查询当前用户的信息 */
	@RequestMapping("/sysUserInfo")
	public String sysUserInfo(String id, Model model){
		//1.根据id查询用户信息
		SysUser sysUser = sysUserService.findById(id);
		System.out.println(sysUser);
		
		//2.将用户信息存入model中(存入request域中)
		model.addAttribute("user", sysUser);
		//3.转向sysUser_update.jsp
		return "sys/user/update";
	}
	
	/** 4.根据id修改用户信息
	 *  4.1.先根据id查询当前用户的信息
	 *  4.2.再根据id修改当前用户的信息 */
	@RequestMapping("/sysUserUpdate")
	public String sysUserUpdate(SysUser sysUser){
		//System.out.println(sysUser);
		//1.调用sysUserService的updateById方法修改用户信息
		sysUserService.updateById(sysUser);
		//2.转向查询所有用户的方法
		return "redirect:/sysUserList";
	}
}
